package com.wxscrmplus.riskcontrol.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.wxscrmplus.common.core.domain.entity.SysUser;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.StreamUtils;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.riskcontrol.domain.RiskInterceptRule;
import com.wxscrmplus.riskcontrol.domain.bo.RiskInterceptRuleBo;
import com.wxscrmplus.riskcontrol.domain.vo.RiskInterceptRuleVo;
import com.wxscrmplus.riskcontrol.mapper.RiskInterceptRuleMapper;
import com.wxscrmplus.riskcontrol.service.IRiskInterceptRuleService;
import com.wxscrmplus.system.mapper.SysUserMapper;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.bean.external.interceptrule.ApplicableRange;
import me.chanjar.weixin.cp.bean.external.interceptrule.WxCpInterceptRule;
import me.chanjar.weixin.cp.bean.external.interceptrule.WxCpInterceptRuleAddRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 敏感词控Service业务层处理
 *
 * @author 王永超
 * @date 2023-04-16
 */
@RequiredArgsConstructor
@Service
public class RiskInterceptRuleServiceImpl extends WxCpServiceFactory implements IRiskInterceptRuleService {

    private final RiskInterceptRuleMapper baseMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询敏感词控
     */
// 361980441c1674cb0b19d312a8085b6d
    @Override
    public RiskInterceptRuleVo queryById(Long ruleId) {
        return baseMapper.selectVoById(ruleId);
    }

    /**
     * 查询敏感词控列表
     */
    @Override
    public TableDataInfo<RiskInterceptRuleVo> queryPageList(RiskInterceptRuleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RiskInterceptRule> lqw = buildQueryWrapper(bo);
        Page<RiskInterceptRuleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (RiskInterceptRuleVo record : result.getRecords()) {
            List<SysUser> sysUserList = userMapper.selectVoBatchIds(record.getApplicableUserList());
            record.setApplicableUserNickName(StreamUtils.join(sysUserList, SysUser::getNickName));
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询敏感词控列表
     */
    @Override
    public List<RiskInterceptRuleVo> queryList(RiskInterceptRuleBo bo) {
        LambdaQueryWrapper<RiskInterceptRule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<RiskInterceptRule> buildQueryWrapper(RiskInterceptRuleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RiskInterceptRule> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getRuleName()), RiskInterceptRule::getRuleName, bo.getRuleName());
        lqw.orderByDesc(RiskInterceptRule::getRuleId);
        return lqw;
    }

    /**
     * 新增敏感词控
     */
    @Transactional
    @Override
    public Boolean insertByBo(RiskInterceptRuleBo bo) {
        RiskInterceptRule add = BeanUtil.toBean(bo, RiskInterceptRule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRuleId(add.getRuleId());
        }
        WxCpInterceptRuleAddRequest wxCpInterceptRuleResp = new WxCpInterceptRuleAddRequest();
        wxCpInterceptRuleResp.setInterceptType(bo.getInterceptType());
        wxCpInterceptRuleResp.setRuleName(bo.getRuleName());
        wxCpInterceptRuleResp.setWordList(bo.getWordList());
        wxCpInterceptRuleResp.setSemanticsList(bo.getSemanticsList());
        ApplicableRange applicableRange = new ApplicableRange();
        List<SysUser> sysUserList = userMapper.selectVoBatchIds(bo.getApplicableUserList());
        applicableRange.setUserList(StreamUtils.toList(sysUserList, SysUser::getUserName));
        wxCpInterceptRuleResp.setApplicableRange(applicableRange);
        try {
            add.setQwRuleId(getExternalContactService().addInterceptRule(wxCpInterceptRuleResp));
            if (baseMapper.updateById(add) < 1) {
                throw new ServiceException("系统错误");
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    /**
     * 修改敏感词控
     */
    @Override
    public Boolean updateByBo(RiskInterceptRuleBo bo) {
        RiskInterceptRule update = BeanUtil.toBean(bo, RiskInterceptRule.class);
        validEntityBeforeSave(update);
        RiskInterceptRule riskInterceptRule = baseMapper.selectById(bo.getRuleId());
        WxCpInterceptRule cpInterceptRule = new WxCpInterceptRule();
        cpInterceptRule.setRuleId(riskInterceptRule.getQwRuleId());
        cpInterceptRule.setInterceptType(bo.getInterceptType());
        cpInterceptRule.setRuleName(bo.getRuleName());
        cpInterceptRule.setWordList(bo.getWordList());
        WxCpInterceptRule.ExtraRule extraRule = new WxCpInterceptRule.ExtraRule();
        extraRule.setSemanticsList(bo.getSemanticsList());
        cpInterceptRule.setExtraRule(extraRule);
        ApplicableRange applicableRange = new ApplicableRange();
        List<SysUser> sysUserList = userMapper.selectVoBatchIds(bo.getApplicableUserList());
        applicableRange.setUserList(StreamUtils.toList(sysUserList, SysUser::getUserName));
        cpInterceptRule.setApplicableRange(applicableRange);
        try {
            getExternalContactService().updateInterceptRule(cpInterceptRule);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RiskInterceptRule entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除敏感词控
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<RiskInterceptRule> riskInterceptRules = baseMapper.selectBatchIds(ids);
        WxCpExternalContactService externalContactService = getExternalContactService();
        for (RiskInterceptRule riskInterceptRule : riskInterceptRules) {
            try {
                externalContactService.delInterceptRule(riskInterceptRule.getQwRuleId());
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
